package com.atlin.project.controller;

import com.atlin.project.annotation.AuthCheck;
import com.atlin.project.common.BaseResponse;
import com.atlin.project.common.DeleteRequest;
import com.atlin.project.common.ErrorCode;
import com.atlin.project.common.ResultUtils;
import com.atlin.project.contant.UserConstant;
import com.atlin.project.exception.BusinessException;
import com.atlin.project.exception.ThrowUtils;
import com.atlin.project.model.domain.SysUser;
import com.atlin.project.model.domain.SysAnnouncement;
import com.atlin.project.model.dto.sysAnnouncement.SysAnnouncementAddRequest;
import com.atlin.project.model.dto.sysAnnouncement.SysAnnouncementQueryRequest;
import com.atlin.project.model.dto.sysAnnouncement.SysAnnouncementUpdateRequest;
import com.atlin.project.model.vo.sysAnnouncement.SysAnnouncementVO;
import com.atlin.project.service.SysUserService;
import com.atlin.project.service.SysAnnouncementService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 系统公告接口
 *
 * @author atlin
 */
@RestController
@RequestMapping("/sysAnnouncement")
public class SysAnnouncementController {

    @Resource
    private SysAnnouncementService sysAnnouncementService;

    @Resource
    private SysUserService sysUserService;

    private final static Gson GSON = new Gson();

    // region 增删改查

    /**
     * 创建
     *
     * @param sysAnnouncementAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addSysAnnouncement(@RequestBody SysAnnouncementAddRequest sysAnnouncementAddRequest, HttpServletRequest request) {
        if (sysAnnouncementAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        SysUser loginUser = sysUserService.getLoginUser(request);
        SysAnnouncement sysAnnouncement = new SysAnnouncement();
        BeanUtils.copyProperties(sysAnnouncementAddRequest, sysAnnouncement);
        sysAnnouncement.setUserId(loginUser.getId());

        sysAnnouncementService.valid(sysAnnouncement, true);

        boolean result = sysAnnouncementService.save(sysAnnouncement);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);

        long newSysAnnouncementId = sysAnnouncement.getId();
        return ResultUtils.success(newSysAnnouncementId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteSysAnnouncement(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        SysUser user = sysUserService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        SysAnnouncement oldsysAnnouncement = sysAnnouncementService.getById(id);
        ThrowUtils.throwIf(oldsysAnnouncement == null, ErrorCode.NULL_ERROR);

        // 仅本人或管理员可删除
        if (!oldsysAnnouncement.getUserId().equals(user.getId()) && !sysUserService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = sysAnnouncementService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param sysAnnouncementUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateSysAnnouncement(@RequestBody SysAnnouncementUpdateRequest sysAnnouncementUpdateRequest) {
        if (sysAnnouncementUpdateRequest == null || sysAnnouncementUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        SysAnnouncement sysAnnouncement = new SysAnnouncement();
        BeanUtils.copyProperties(sysAnnouncementUpdateRequest, sysAnnouncement);

        // 参数校验
        sysAnnouncementService.valid(sysAnnouncement, false);
        long id = sysAnnouncementUpdateRequest.getId();
        // 判断是否存在
        SysAnnouncement oldsysAnnouncement = sysAnnouncementService.getById(id);
        ThrowUtils.throwIf(oldsysAnnouncement == null, ErrorCode.NULL_ERROR);

        boolean result = sysAnnouncementService.updateById(sysAnnouncement);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<SysAnnouncement> getSysAnnouncementById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        SysAnnouncement sysAnnouncement = sysAnnouncementService.getById(id);
        if (sysAnnouncement == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        SysUser loginUser = sysUserService.getLoginUser(request);
        // 不是本人或管理员，不能直接获取所有信息
        if (!sysAnnouncement.getUserId().equals(loginUser.getId()) && !sysUserService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        return ResultUtils.success(sysAnnouncement);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<SysAnnouncementVO> getSysAnnouncementVOById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        SysAnnouncement sysAnnouncement = sysAnnouncementService.getById(id);
        if (sysAnnouncement == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }

        SysAnnouncementVO sysAnnouncementVO = SysAnnouncementVO.objToVo(sysAnnouncement);
        return ResultUtils.success(sysAnnouncementVO);
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param sysAnnouncementQueryRequest 查询参数
     * @param request                     查询请求
     * @return 分页封装类
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<SysAnnouncementVO>> listSysAnnouncementVOByPage(@RequestBody SysAnnouncementQueryRequest sysAnnouncementQueryRequest,
                                                                             HttpServletRequest request) {
        long current = sysAnnouncementQueryRequest.getCurrent();
        long size = sysAnnouncementQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<SysAnnouncement> sysAnnouncementPage = sysAnnouncementService.page(new Page<>(current, size),
                sysAnnouncementService.getQueryWrapper(sysAnnouncementQueryRequest));

        Page<SysAnnouncementVO> sysAnnouncementVOPage = sysAnnouncementService.getSysAnnouncementVOPage(sysAnnouncementPage, request);

        return ResultUtils.success(sysAnnouncementVOPage);
    }

    /**
     * 分页获取列表（仅管理员）
     *
     * @param sysAnnouncementQueryRequest 查询参数
     * @param request                     查询请求
     * @return 分页
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<SysAnnouncement>> listSysAnnouncementByPage(@RequestBody SysAnnouncementQueryRequest sysAnnouncementQueryRequest,
                                                                         HttpServletRequest request) {
        long current = sysAnnouncementQueryRequest.getCurrent();
        long size = sysAnnouncementQueryRequest.getPageSize();
        Page<SysAnnouncement> sysAnnouncementPage = sysAnnouncementService.page(new Page<>(current, size),
                sysAnnouncementService.getQueryWrapper(sysAnnouncementQueryRequest));
        return ResultUtils.success(sysAnnouncementPage);
    }

    // endregion

}
